import { defineStore } from 'pinia'
import { storage } from '~/utils/storage'

interface LoginForm {
  email: string
  password: string
  remember?: boolean
}

interface RegisterForm {
  username: string
  email: string
  password: string
  confirmPassword: string
}

// 认证状态管理
export const useAuthStore = defineStore('auth', () => {
  // TODO: 实现认证状态
  const token = ref<string | null>(null) // 令牌
  const refreshToken = ref<string | null>(null) // 刷新令牌
  const isLoggedIn = computed(() => !!token.value) // 是否登录

  // 从 localStorage 恢复令牌
  function initAuth(){
    token.value = storage.get('token');
    refreshToken.value = storage.get('refreshToken');
  }

  // 登录
  async function login(from:LoginForm){
    try {
        const {data} = await $fetch('/api/auth/login',{
            method:'POST',
            body:from
        }) as any

        token.value = data.token;
        refreshToken.value = data.refreshToken;
        if(from.remember){
            storage.set('token',data.token,7*24*60*60); // 7天
            storage.set('refreshToken',data.refreshToken,30*24*60*60); // 30天
        }else{
            storage.set('token',data.token);
            storage.set('refreshToken',data.refreshToken);
        }
        
        // 保存用户信息到 user store
        if(data.user){
            const userStore = useUserStore();
            userStore.user = data.user;
        }
        
        return {success:true,message:'登录成功'}
    } catch (error:any) {
        return {success:false,message:error.message || '登录失败'}
    }
  }


  // 注册
  async function register(from:RegisterForm){
    try {
        const {data} = await $fetch('/api/auth/register',{
            method:'POST',
            body:from
        }) as any

        token.value = data.token;
        refreshToken.value = data.refreshToken;
        storage.set('token',data.token);
        storage.set('refreshToken',data.refreshToken);
        
        // 保存用户信息到 user store
        if(data.user){
            const userStore = useUserStore();
            userStore.user = data.user;
        }
        
        return {success:true,message:'注册成功'}
    } catch (error:any) {
        return {success:false,message:error.message || '注册失败'}
    }
  }

  // 退出登录
  function logout(){
    token.value = null;
    refreshToken.value = null;
    storage.remove('token');
    storage.remove('refreshToken');

    // 清除用户信息
    const userStore = useUserStore();
    userStore.$reset();

    // 跳转到登录页
    navigateTo('/auth/login');
  }

  // 刷新令牌
  async function refreshAuthToken(){
    try {
        const {data} = await $fetch('/api/auth/refresh',{
            method:'POST',
            body:{refreshToken:refreshToken.value}
        }) as any
        token.value = data.token;
        storage.set('token',data.token);
        return true
    } catch (error:any) {
        logout();
        return {success:false,message:error.message}
    }
  }

  return {
    token,
    refreshToken,
    isLoggedIn,
    initAuth,
    login,
    register,
    logout,
    refreshAuthToken,
  }
})

